<template>
  <div>
    <div id="gdMapContainer" :style="{ width: detail.style.position.w + 'px', height: detail.style.position.h + 'px' }">
    </div>
    <div class="info_window">
      <el-select v-model="deviceMac" filterable placeholder="请选择" @change="handleChange">
        <el-option v-for="item in deviceData" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
    </div>
  </div>
</template>

<script>

import BaseView from './View';
import offLineImg from '@/views/zutai/images/offLine.png'
import onLineImg from '@/views/zutai/images/onLine.png'
import request from '@/utils/request';
import warnLineImg from '@/views/zutai/images/warnLine.png'

export default {
  name: 'view-map',
  extends: BaseView,
  components: {},
  data() {
    return {
      onLineImg: onLineImg,
      warnLineImg: warnLineImg,
      offLineImg: offLineImg,
      timer: null,
      center: [116.333926, 39.997245],
      deviceMac: '',
      deviceData: [],
      mapType: '',
      zoom: 15,
      map: null,
      mapList: []
    };
  },
  computed: {
    mapStyleChange() {
      return this.detail.style.mapType + '-' + this.detail.style.mapModel + "-" + this.detail.style.zoom + this.detail.style.pitch
          + "-" + this.detail.style.mapContent + "-" + this.detail.style.skyColor;
    }
  },
  watch: {
    mapStyleChange() {
      this.initMap();
    },
  },
  mounted() {
    this.getList('init');
    this.timer = setInterval(this.getList, 60000 * 10);
  },
  beforeDestroy() {
    clearInterval(this.timer);
    this.timer = null;
    if (this.map) {
      this.map.destroy();
    }
  },
  methods: {
    handleChange() {
      this.getList();
    },
    getList(label) {
      let url = "/zutai/bDeviceManager/list"
      let param = {
        pageNum: 1,
        pageSize: 9999,
        deviceMac: this.deviceMac
      }
      request({
        url: url,
        method: "get",
        params: param,

      }).then((res) => {
        this.mapList = res.rows;
        if (res.rows.length > 0) {
          this.center = [res.rows[0].longitude, res.rows[0].latitude];
        }
        this.initMap();
        if (label == 'init') {
          this.deviceData = [{
            label: '全部',
            value: ''
          }]
          res.rows.forEach(element => {
            let data = {
              label: element.deviceName,
              value: element.deviceMac
            }
            this.deviceData.push(data)
          });
        }
      })
    },
    initMap() {
      this.map = new AMap.Map('gdMapContainer', {
        rotateEnable: true,
        pitchEnable: true,
        zoom: this.detail.style.zoom,
        pitch: this.detail.style.pitch,
        rotation: -15,
        viewMode: this.detail.style.mapType, //开启3D视图,默认为关闭
        zooms: [2, 20],
        center: this.center,
        features: this.detail.style.mapContent,//地图要素,['bg', 'road', 'building', 'point']
        skyColor: this.detail.style.skyColor
      });
      var controlBar = new AMap.ControlBar({
        position: {
          right: '10px',
          top: '10px'
        }
      });
      controlBar.addTo(this.map);

      var toolBar = new AMap.ToolBar({
        position: {
          right: '40px',
          top: '110px'
        }
      });
      toolBar.addTo(this.map);
      this.setMapStyle();
      this.setMapMarker();

    },
    setMapStyle() {
      var styleName = "amap://styles/" + this.detail.style.mapModel;
      this.map.setMapStyle(styleName);
    },
    // 增加点标记
    setMapMarker() {
      //信息窗口实例
      this.infoWindow = new AMap.InfoWindow({
        anchor: "top-left",
        offset: new AMap.Pixel(0, 0)
      });
      let makerList = []
      this.mapList.forEach((item, i) => {
        // 创建 AMap.Icon 实例
        let icon = new AMap.Icon({
          size: new AMap.Size(36, 36), // 图标尺寸
          image: [offLineImg, onLineImg, warnLineImg][item.deviceStatus], // Icon的图像
          imageSize: new AMap.Size(30, 30), // 根据所设置的大小拉伸或压缩图片
          imageOffset: new AMap.Pixel(0, 0)  // 图像相对展示区域的偏移量，适于雪碧图等
        });
        let gdPosition = this.bd_decrypt(item.longitude, item.latitude)
        // 遍历生成多个标记点
        let marker = new AMap.Marker({
          map: this.map,
          zIndex: 9999,
          icon: icon, // 添加 Icon 实例
          offset: new AMap.Pixel(-13, -30), //icon中心点的偏移量
          position: [gdPosition.lng, gdPosition.lat] // 经纬度对象new AMap.LngLat(x, y)，也可以是经纬度构成的一维数组[116.39, 39.9]
        });
        let deviceStatus = '';
        if (item.deviceStatus == 1) {
          deviceStatus = `设备状态：<span style="color:#67C23A">在线</span>`
        } else if (item.deviceStatus == 2) {
          deviceStatus = `设备状态：<span style="color:#F56C6C">报警</span>`
        } else {
          deviceStatus = `设备状态：<span style="color:#909399">离线</span>`
        }
        var infoWindowContent = `<div>` +
            `<p>设备编号：` + item.deviceMac + `</p>` +
            `<p>设备名称：` + item.deviceName + `</p>` +
            `<p>设备地址：` + item.installationAddress + `</p>` +
            deviceStatus +
            `</div>`;
        marker.content = infoWindowContent
        marker.on("click", this.markerClick)
        marker.emit('click', {target: marker});// 此处是设置默认出现信息窗体
        makerList.push(marker)
      });
      this.makerList = makerList
      this.map.add(makerList)
      // 自动适应显示想显示的范围区域
      this.map.setFitView();
    },
    // 控制标记的信息窗体的显示
    markerClick(e) {
      // 标注的点击事件
      this.infoWindow.setContent(e.target.content);
      this.infoWindow.open(this.map, e.target.getPosition());
    },
    // 百度-高德坐标
    bd_decrypt(bd_lng, bd_lat) {
      var X_PI = Math.PI * 3000.0 / 180.0
      var x = bd_lng - 0.0065
      var y = bd_lat - 0.006
      var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI)
      var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI)
      var gg_lng = z * Math.cos(theta)
      var gg_lat = z * Math.sin(theta)
      return {lng: gg_lng, lat: gg_lat}
    },
    // 高德-百度坐标
    gd_decrypt(lng, lat) {
      const xsPI = 3.14159265358979324 * 3000.0 / 180.0
      const bdlat = Number(lat)
      const bdlng = Number(lng)
      const z = Math.sqrt(bdlng * bdlng + bdlat * bdlat) + 0.00002 * Math.sin(bdlat * xsPI)
      const theta = Math.atan2(bdlat, bdlng) + 0.000003 * Math.cos(bdlng * xsPI)
      const bdslng = z * Math.cos(theta) + 0.0065
      const bdslat = z * Math.sin(theta) + 0.006
      return [bdslng, bdslat] // 注意啊，我这里为了方便，所以返回的是数组，不是对象
    }
  }
};
</script>
<style scoped>
.info_window {
  background-color: #FAF9F7;
  opacity: 0.8;
  position: absolute;
  top: 10px;
  left: 10px;
  border-radius: 1%;
  box-shadow: 0 0 10px 0 red;
  z-index: 99999;
}
</style>
<style>
.BMap_cpyCtrl {
  display: none;
}

.anchorBL {
  display: none;
}
</style>
